package Tydzien11;

import java.awt.Color;
import java.sql.*;
import java.util.ArrayList;
import java.util.Calendar;

import Tydzien10.OrganizerEvent;

public abstract class OrganizerEventsDatabase {
	public static void saveToDatabase(ArrayList<OrganizerEvent> events) throws SQLException
	{
		try(Connection con = DriverManager.getConnection("jdbc:jtds:sqlserver://LAPEK/OrganizerEvents;instance=MSSQLSERVER")) {
			con.setAutoCommit(false);
			try(Statement killStatement = con.createStatement();
				PreparedStatement statement = con.prepareStatement("INSERT INTO Events (startDate, endDate, descript, r, g, b) "
																 + "VALUES ((?), (?), (?), (?), (?), (?))")) {
				killStatement.executeUpdate("DELETE FROM Events");
					
				for(OrganizerEvent event : events)
				{
					statement.setTimestamp(1, new Timestamp(event.getEventStart().getTimeInMillis()));
					statement.setTimestamp(2, new Timestamp(event.getEventEnd().getTimeInMillis()));
					statement.setString(3, event.getDescription());
					float[] colors = event.getColor().getColorComponents(null);
					statement.setFloat(4, colors[0]);
					statement.setFloat(5, colors[1]);
					statement.setFloat(6, colors[2]);
					
					statement.executeUpdate();
				}
				con.commit();
			}
		}
	}
	
	public static ArrayList<OrganizerEvent> loadFromDatabase() throws SQLException
	{
		try(Connection con = DriverManager.getConnection("jdbc:jtds:sqlserver://LAPEK/OrganizerEvents;instance=MSSQLSERVER");
			Statement statement = con.createStatement();
			ResultSet rs = statement.executeQuery("SELECT * FROM Events")) {
			
			ArrayList<OrganizerEvent> events = new ArrayList<OrganizerEvent>();
			
			while(rs.next())
			{
				Calendar startDate = Calendar.getInstance(); 
				startDate.setTime(rs.getTimestamp("startDate"));
				
				Calendar endDate = Calendar.getInstance(); 
				endDate.setTime(rs.getTimestamp("endDate"));
				
				String description = rs.getString("descript");
				
				Color color = new Color(rs.getFloat("r"), rs.getFloat("g"), rs.getFloat("b"));
				
				events.add(new OrganizerEvent(startDate, endDate, description, color));
			}
			
			return events;
		}
	}
}
